﻿using System.Text;

namespace TPXSDK.NET.Mission.Instruction;

internal class InstFlyto : Tokenizer
{
    public InstFlyto(TokenizerAdmin admin)
    {
        Admin = admin;
        KeyName = "flyto";
        KeyValue = (int)FlyCmdId.CMD_FLYTO;
        Usage = "flyto (waypoint) [,alt]";
        Description = @"flyto (waypoint) [,alt]: Fly to the waypoint. The flyto command sets the desired heading.";
    }

    public override bool Process()
    {
        var flyCmp = Admin?.Compiler; if (null == flyCmp) return false;
        var tokens = flyCmp.GetLineTokens();
        if (null == tokens) return false;

        if (tokens.Count != 2 && tokens.Count != 3)
        {
            flyCmp.ErrorMsg = $"{KeyName} Invalid Usage";
            return false;
        }

        var result = false;
        var cmd = new FlyCmdItem
        {
            Id = (byte)KeyValue,
            LineNum = tokens[0].Row
        };
        tokens.RemoveAt(0);// Remove Flycmd Name
        if (tokens[0].Type == TokenType.ABS_POS
          || tokens[0].Type == TokenType.REL_POS)
        {//flyto (xxx, xxx)形式
            result = FlyUtils.WpToken2CmdItemP1(tokens[0], cmd);
        }

        if (result)
        {
            if (tokens.Count == 2 && tokens[1].Type == TokenType.NUMBER)
            {
                cmd.P2 = FlyUtils.ToInt16(tokens[1].Name);
            }

            /* mark for fast waypoint mode */
            if (flyCmp.FastWpMode) cmd.P1 |= 0x80;
            flyCmp.FastWpMode = false;// 仅对当前Flyto指令生效
            flyCmp.CmdList.Add(cmd);
        }
        else
        {
            flyCmp.ErrorMsg = $"{KeyName} Invalid param";
        }

        return result;
    }

    public override void Reverse(FlyCmdItem cmd, StringBuilder sb)
    {
        var fastwp = 0 != (cmd.P1 & 0x80);
        if (fastwp)
        {
            sb.AppendLine("fastwp");
        }

        sb.AppendLine(cmd.P2 == 0
            ? $"{KeyName} {FlyUtils.ParseWpFromCmdItem(cmd)}"
            : $"{KeyName} {FlyUtils.ParseWpFromCmdItem(cmd)}, {cmd.P2}");
    }
}
